<template>
	<view class="container">
		<!-- 证书列表 -->
		<view class="content">
			<!-- 无证书时显示 -->
			<view v-if="!certList || certList.length === 0" class="no-cert bg-white rounded-xl p-5 text-center">
				<image src="https://via.placeholder.com/150" mode="aspectFit" style="width: 200rpx; height: 200rpx; margin: 0 auto 30rpx;"></image>
				<view class="text-lg text-gray-600">暂无证书</view>
				<view class="text-sm text-gray-500 mt-2">您还没有获得任何证书</view>
			</view>
			
			<!-- 证书卡片 -->
			<view v-for="(cert, index) in certList" :key="index" class="cert-card bg-white rounded-xl overflow-hidden animate-fade-in">
				<view class="p-5">
					<view class="flex justify-between items-start mb-3">
						<view>
							<view class="text-lg font-bold text-gray-800 flex items-center">
								心长征路培训证书
							</view>
							<view class="text-sm text-gray-500 mt-1">颁发机构: 盛心海发</view>
						</view>
					</view>

					<view class="flex justify-between text-sm text-gray-600 mb-4">
						<view>获得时间: {{cert.certDate}}</view>
						<view>有效期至: {{cert.year}}-{{cert.month}}-{{cert.endDay}}</view>
					</view>

					<view class="cert-image-placeholder rounded-lg overflow-hidden mb-4 flex items-center justify-center">
						<image :src="certImageUrl" mode="aspectFit" style="width: 100%; height: auto;"></image>
					</view>

					<view class="flex justify-end space-x-3">
						<button @tap="downloadCert(cert, '心长征路培训证书')"
							class="btn-download flex items-center px-4 py-2 bg-emerald-500 hover:bg-emerald-600 text-white rounded-lg transition-colors">
							<text class="iconfont icon-download mr-2"></text>下载证书
						</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 隐藏的canvas，用于合成图片 -->
		<canvas canvas-id="certCanvas" id="certCanvas" style="position: fixed; top: -9999px; left: -9999px; width: 3508px; height: 2480px;"></canvas>
	</view>
</template>

<script>
	import {
		getCertList,
	} from "../../utils/getDate.js";
	export default {
		data() {
			return {
				activeTab: 'all',
				certList: [],
				certImageUrl: "https://lesson.iapeap.com/images/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250721171803%20%281%29.png",
				canvasWidth: 3508, // 设置为证书图片的原始宽度
				canvasHeight: 2480 // 设置为证书图片的原始高度
			}
		},
		onLoad() {
			this.ongetCertList();
		},
		methods: {
			ongetCertList() {
				const data = {
					userId: uni.getStorageSync("userinfo").id
				}

				getCertList(data).then(res => {
					if (res.state === 'ok') {
						this.certList = res.data;
					} else {
						this.certList = [];
					}
				}).catch(err => {
					console.error('获取证书列表失败:', err);
					this.certList = [];
				})
			},

			// 下载证书
			async downloadCert(certData, title) {
			    uni.showLoading({
			        title: '生成证书中...',
			        mask: true
			    });
			    try {
			        const tempFilePath = await this.downloadImage(this.certImageUrl);
			        const ctx = uni.createCanvasContext('certCanvas', this);
			        ctx.drawImage(tempFilePath, 0, 0, this.canvasWidth, this.canvasHeight);
			        ctx.setFontSize(60);
			        ctx.setFillStyle('#000000');
			        ctx.fillText(certData.name, 450, 1150);
					ctx.fillText(certData.year, 1030, 1150);
					ctx.fillText(certData.month, 1300, 1150);
					ctx.fillText(certData.startDay, 1480, 1150);
					ctx.fillText(certData.endDay, 1780, 1150);
					ctx.fillText(certData.code, 940, 2040);
			        await new Promise((resolve, reject) => {
			            ctx.draw(false, () => {
			                setTimeout(() => {
			                    this.saveCanvasToImage();
			                    resolve();
			                }, 300);
			            });
			        });
			    } catch (error) {
			        console.error('生成证书失败:', error);
			        uni.hideLoading();
			        uni.showToast({
			            title: '生成证书失败',
			            icon: 'none'
			        });
			    }
			},
			
			// 新增方法：下载图片到本地
			downloadImage(url) {
			    return new Promise((resolve, reject) => {
			        uni.downloadFile({
			            url: url,
			            success: (res) => {
			                if (res.statusCode === 200) {
			                    resolve(res.tempFilePath);
			                } else {
			                    reject(new Error('下载图片失败'));
			                }
			            },
			            fail: reject
			        });
			    });
			},
			
			// 获取图片信息
			getImageInfo(src) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: src,
						success: resolve,
						fail: reject
					});
				});
			},
			
			// 将canvas保存为图片
			saveCanvasToImage() {
				uni.canvasToTempFilePath({
					canvasId: 'certCanvas',
					quality: 1, // 最高质量
					fileType: 'png',
					width: this.canvasWidth,
					height: this.canvasHeight,
					success: (res) => {
						const tempFilePath = res.tempFilePath;
						uni.hideLoading();
						
						// 保存到相册
						uni.saveImageToPhotosAlbum({
							filePath: tempFilePath,
							success: () => {
								uni.showToast({
									title: '证书保存成功',
									icon: 'success'
								});
							},
							fail: (err) => {
								console.error('保存失败:', err);
								uni.showToast({
									title: '保存失败，请重试',
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('生成图片失败:', err);
						uni.hideLoading();
						uni.showToast({
							title: '生成证书失败',
							icon: 'none'
						});
					}
				}, this);
			}
		}
	}
</script>

<style>
	/* 全局样式 */
	page {
		font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
		background-color: #f8f9fa;
		color: #333;
		-webkit-font-smoothing: antialiased;
		max-width: 100%;
	}

	.container {
		max-width: 750rpx;
		margin: 0 auto;
		background-color: #fff;
		min-height: 100vh;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
	}

	.content {
		padding: 32rpx;
	}

	/* 无证书样式 */
	.no-cert {
		padding: 60rpx 32rpx;
		margin-top: 100rpx;
		box-shadow: 0 12rpx 36rpx rgba(0, 0, 0, 0.05);
	}

	/* 导航栏样式 */
	.nav-demo {
		position: relative;
		height: 120rpx;
		background-color: #007AFF;
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		color: white;
		overflow: hidden;
	}

	.nav-demo::before {
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 40rpx;
		background-color: rgba(255, 255, 255, 0.1);
	}

	/* 证书卡片样式 */
	.cert-card {
		transition: all 0.3s ease;
		box-shadow: 0 12rpx 36rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 32rpx;
	}

	.cert-card:active {
		transform: translateY(-8rpx);
		box-shadow: 0 24rpx 48rpx rgba(0, 0, 0, 0.1);
	}

	.status-badge {
		font-size: 24rpx;
		letter-spacing: 1rpx;
	}

	.search-input:focus {
		box-shadow: 0 0 0 6rpx rgba(5, 150, 105, 0.2);
	}

	.nav-tab {
		transition: all 0.2s ease;
	}

	.nav-tab:active:not(.active) {
		background-color: rgba(5, 150, 105, 0.08);
	}

	.cert-image-placeholder {
		background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
	}

	.animate-fade-in {
		animation: fadeIn 0.5s ease-out;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	/* 工具类样式 */
	.flex {
		display: flex;
	}

	.flex-1 {
		flex: 1;
	}

	.items-center {
		align-items: center;
	}

	.justify-between {
		justify-content: space-between;
	}

	.justify-end {
		justify-content: flex-end;
	}

	.justify-center {
		justify-content: center;
	}

	.text-center {
		text-align: center;
	}

	.text-lg {
		font-size: 36rpx;
	}

	.text-sm {
		font-size: 28rpx;
	}

	.text-xs {
		font-size: 24rpx;
	}

	.font-bold {
		font-weight: bold;
	}

	.font-medium {
		font-weight: 500;
	}

	.text-gray-800 {
		color: #333;
	}

	.text-gray-500 {
		color: #666;
	}

	.text-gray-600 {
		color: #555;
	}

	.text-gray-700 {
		color: #444;
	}

	.text-white {
		color: white;
	}

	.text-emerald-500 {
		color: #10b981;
	}

	.text-emerald-300 {
		color: #6ee7b7;
	}

	.text-blue-500 {
		color: #3b82f6;
	}

	.text-blue-300 {
		color: #93c5fd;
	}

	.text-purple-500 {
		color: #8b5cf6;
	}

	.text-purple-300 {
		color: #c4b5fd;
	}

	.bg-white {
		background-color: white;
	}

	.bg-emerald-500 {
		background-color: #10b981;
	}

	.bg-emerald-600 {
		background-color: #059669;
	}

	.bg-blue-500 {
		background-color: #3b82f6;
	}

	.bg-blue-600 {
		background-color: #2563eb;
	}

	.bg-purple-500 {
		background-color: #8b5cf6;
	}

	.bg-purple-600 {
		background-color: #7c3aed;
	}

	.bg-gray-100 {
		background-color: #f3f4f6;
	}

	.bg-gray-200 {
		background-color: #e5e7eb;
	}

	.bg-blue-50 {
		background-color: #eff6ff;
	}

	.bg-purple-50 {
		background-color: #f5f3ff;
	}

	.rounded-lg {
		border-radius: 16rpx;
	}

	.rounded-xl {
		border-radius: 24rpx;
	}

	.rounded-full {
		border-radius: 9999px;
	}

	.p-5 {
		padding: 40rpx;
	}

	.px-4 {
		padding-left: 32rpx;
		padding-right: 32rpx;
	}

	.py-2 {
		padding-top: 16rpx;
		padding-bottom: 16rpx;
	}

	.mb-3 {
		margin-bottom: 24rpx;
	}

	.mb-4 {
		margin-bottom: 32rpx;
	}

	.mt-1 {
		margin-top: 8rpx;
	}

	.mr-1 {
		margin-right: 8rpx;
	}

	.mr-2 {
		margin-right: 16rpx;
	}

	.space-x-3>view+view,
	.space-x-3>button+button {
		margin-left: 24rpx;
	}

	.overflow-hidden {
		overflow: hidden;
	}

	.truncate {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/* 按钮样式 */
	button {
		margin: 0;
		padding: 0;
		background: none;
		border: none;
		line-height: 1;
	}

	button::after {
		border: none;
	}

	.btn-download,
	.btn-share {
		transition: background-color 0.3s;
	}

	/* 图标样式 */
	.iconfont {
		font-family: "iconfont" !important;
		font-size: inherit;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	/* 这里需要替换为你实际的iconfont CSS内容 */
	.icon-certificate:before {
		content: "\e6c1";
	}

	.icon-calendar:before {
		content: "\e6c2";
	}

	.icon-clock:before {
		content: "\e6c3";
	}

	.icon-download:before {
		content: "\e6c4";
	}

	.icon-share:before {
		content: "\e6c5";
	}
</style>